<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view>
    <view style="flex: 1; overflow: auto; position: relative">
      <!-- v-for="item in form.rdProjectUserEntity.filter(
            (item) => item.signatureFlag == 1 || (item.documentsPostCode == '255' && item.userUrl),
          )" -->
      <th-form>
        <th-form-item label="评审状态">
          <text class="text">
            <view v-if="form.rdFlag == '1'" class="result-tag">通过</view>
            <view v-else-if="form.rdFlag == '0'" class="result-tag" style="background-color: #f50">
              不通过
            </view>
          </text>
        </th-form-item>
        <th-form-item label="评审意见" class="form-demandDesc">
          <text class="text">{{ form.requirements }}</text>
        </th-form-item>
        <th-form-item
          v-for="item in form.rdProjectUserEntity.filter((item) => item.signatureFlag == 1)"
          :label="item.documentsPostName"
        >
          <!--  @click="preview(getProjectName(item, 1))" -->
          <wd-img :width="200" :height="100" :src="getProjectName(item, 1)" />
        </th-form-item>

        <th-form-item
          v-for="item in form.rdProjectUserEntity.filter(
            (item) => item.documentsPostCode == '255' && item.userUrl,
          )"
          :label="item.documentsPostName"
        >
          <!--  @click="preview(getProjectName(item, 1))" -->
          <wd-img :width="200" :height="100" :src="getProjectName(item, 1)" />
        </th-form-item>
      </th-form>

      <view :class="['sign-main', 'bg-white']" v-if="showSignProject" @click="sign">签字</view>
    </view>

    <wd-action-sheet v-model="showAction" title="" @close="closeSign" @click-modal="closeSign">
      <view class="sign-main-show">
        <!-- <text class="sign-main-show-title">签字</text> -->
        <view class="sign-main-show-line">
          <!-- <wd-img :width="200" :height="100" :src="signature" @click="preview(signature)" /> -->
          <wd-img :width="200" :height="100" :src="signature" @click="signThis" />
        </view>
        <!-- <view class="sign-main-show-btn" @click="signThis">使用该签字</view> -->
        <view class="sign-main-show-btn" @click="signReset">重新签字</view>
      </view>
    </wd-action-sheet>
  </view>
</template>

<script lang="ts" setup>
import { useSetting } from '@/stores/setting';
import { getObj, getPersonByPersonCode, uploadSignature } from '@/service/pm-task';
import { formatByDayjs } from '@/utils/util';
import { useUserStore } from '@/stores/user';
import {
  selectrdDocumentsPostUser,
  selectrdDocumentsPostDict,
  updateSignHandle,
} from '@/service/pm-requirement';
const emit = defineEmits(['refreshDetail', 'signComputed']);

const setting = useSetting();
const userStore = useUserStore();
const showSign = ref(false);
const signature = ref('');
const userInfo = ref({});
const isChiefEngineer = ref('');
const isDeputyChiefEngineer = ref('');
const showAction = ref(false);
const postUserObj: any = ref({});
const rdProjectUserList = ref([]); // 签名列表

// 提交表单数据
const form = ref({
  id: null,
  demandDate: null,
  personName: null,
  demandType: null,
  deptHead: null,
  deptCode: null,
  applicationType: null,
  samplesNum: null,
  demandDesc: null,
  sampleCoding: null,
  askCompleteTime: null,
  taskCode: null,
  userCode: null,
  invName: null,
  invDemand: null,
  sampleFlag: null,
  demandCode: null,
  cusName: null,
  personCode: null,
  deptHeadCode: null,
  cusFlag: '0',
  demandResult: null,
  completeTime: null,
  // technologyHead: null,
  remark: null,
  // technologyHeadCode: null,
  taskId: null,
  instanceId: null,
  invStd: null,
  sampleCode: null,
  sampleBatch: null,
  deptName: null,
  rdFlag: null,
  chiefEngineer: null,
  deputyChiefEngineer: null,
  status: null,
  sampleFlagName: null,
  deputyChiefEngineerUrl: null,
  chiefEngineerUrl: null,
  sampleUnit: null,
  cusCode: null,
  projectCode: null,
  projectName: null,
  rdProjectUser: null,
  projectHead: null,
  completionTime: null,
  // technologyHeadName: null,
  rdInformationDTO: [],
  rdCraftEntity: [],
  rdSampleAnalysisEntity: [],
  rdPlan: null,
  sampleReviewConclusion: null,
  requirements: null,
  projectHeadName: null,
  signedName: null,
  rdProjectUserEntity: [],
  rdTaskListAll: [],
  rdTaskFileEntity: [],
  others: null,
});
const showSignProject = ref(false);
const init = (params) => {
  uni.$off('pm-requirement-sign');
  selectrdDocumentsPostDictList();
  console.log(params, 'paramssssss');
  form.value = params;
  // 判断能不能签字
  const userInfos = userStore.userInfos;
  const cusPerson = userInfos.user.username;

  const o = form.value.rdProjectUserEntity.find((item) => item.userCode == cusPerson);

  console.log('-----o----', o);

  if (o) {
    showSignProject.value = true;
  } else {
    showSignProject.value = false;
  }
  selectrdDocumentsPostUserFn();
};

const sign = () => {
  // uni.navigateTo({
  //   url: '/pages/pm/requirement/sign',
  // });

  // 判断签字
  const userInfos = userStore.userInfos;
  const cusPerson = userInfos.user.username;
  getPersonByPersonCode({
    personCode: cusPerson,
  }).then((res) => {
    const sign = res.data.signature;
    signature.value = sign;
    userInfo.value = res.data;
    if (sign) {
      showAction.value = true;
    } else {
      uni.$on('pm-requirement-sign', (e) => {
        console.log('sign', e);
        signHanle(e);
      });
      uni.navigateTo({
        url: '/pages/pm/requirement/autograph',
      });
    }
  });

  // uni.navigateTo({
  //   url: '/pages/pm/requirement/autograph',
  // });
};

// onPullDownRefresh(() => {
//   init({
//     id: form.value.id,
//     taskCode: form.value.taskCode,
//     demandCode: form.value.demandCode,
//   });
// });

const preview = (url) => {
  if (!url) return;
  uni.previewImage({
    urls: [url],
  });
};

const closeSign = () => {
  showAction.value = false;
  uni.$off('pm-requirement-sign');
};

const signHanle = (sign) => {
  const userInfos: any = userInfo.value;
  const params = {
    demandCode: form.value.demandCode,
    taskCode: form.value.taskCode,
    personId: userInfos.id,
    userName: userInfos.personName,
    userCode: userInfos.personCode,
    userUrl: sign,
    // userType: postUserObj.value.documentsPostCode,
    documentsPostName: postUserObj.value.documentsPostName,
    documentsPostCode: postUserObj.value.documentsPostCode,
    documentsName: postUserObj.value.documentsName,
    documentsCode: postUserObj.value.documentsCode,
    signatureFlag: postUserObj.value.signatureFlag,
    reviewFlag: postUserObj.value.reviewFlag,
    rdCode: form.value.taskCode,
  };

  uni.showLoading({
    mask: true,
  });

  updateSignHandle(params)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          title: '签字成功',
        });

        // setTimeout(() => {
        //   uni.navigateBack();
        // }, 500);

        // 更新签字
        if (!signature.value) {
          uploadSignature({
            id: userInfos.id,
            signature: sign,
          });
        }
        showAction.value = false;
        emit('refreshDetail');
        uni.$emit('refreshList');
        // 刷新页面
        // init({
        //   id: form.value.id,
        //   taskCode: form.value.taskCode,
        //   demandCode: form.value.demandCode,
        // });
      } else {
        uni.showToast({
          mask: true,
          title: `签字失败,原因${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
      emit('signComputed');
      // uni.$off('pm-requirement-sign');
    });
};

const signThis = () => {
  const sign = signature.value;
  signHanle(sign);
};

const signReset = () => {
  uni.$on('pm-requirement-sign', (e) => {
    console.log('sign', e);
    signHanle(e);
  });
  uni.navigateTo({
    url: '/pages/pm/requirement/autograph',
  });
};

const selectrdDocumentsPostDictList = async () => {
  try {
    const res = await selectrdDocumentsPostDict({
      webSql: `documents_code = '2'`,
      size: 1000,
    });
    if (res.code !== 0) {
      return;
    }
    rdProjectUserList.value = res.data.records;
  } catch (err) {
    console.log('err', err);
  }
};

const selectrdDocumentsPostUserFn = () => {
  const userInfos = userStore.userInfos;
  const cusPerson = userInfos.user.username;

  selectrdDocumentsPostUser({
    webSql: `user_code = '${cusPerson}' and documents_code = 2`,
    size: 1000,
  })
    .then((res) => {
      if (res.code == 0) {
        if (res.data.records.length) {
          const lrs = res.data.records.find(
            (item) => item.reviewFlag == 1 && item.signatureFlag == 1,
          );
          const lr = res.data.records.find((item) => item.reviewFlag == 1);
          const l = res.data.records;
          let o: any = {};

          if (lrs.length) {
            o = lrs[0];
          } else if (lr.length) {
            o = lr[0];
          } else {
            o = l[0];
          }
          postUserObj.value = o;
          if (o.reviewFlag == 1 || o.signatureFlag == 1) {
            showSign.value = true;
          } else {
            showSign.value = false;
          }
        } else {
          showSign.value = false;
        }
      } else {
        showSign.value = false;
      }
    })
    .catch(() => {
      showSign.value = false;
    });
};

// type 0 获取姓名 1 获取签名
const getProjectName = (item, type = 0) => {
  console.log(form.value.rdProjectUserEntity, item);
  const l = form.value.rdProjectUserEntity.filter(
    (f) => f.userCode == item.userCode && f.userType == item.documentsPostCode,
  );
  let s = '';
  if (l.length) {
    console.log('s', s);
    if (type == 0) {
      s = l.map((item) => item.userName).join(',');
      return s;
    } else {
      // s = l.map((item) => item.userUrl).join(',');
      s = l[0]['userUrl'];
      return s;
    }
  } else {
    return s;
  }
};

const taskTypeList = ref([]);
const rdTaskListAllActiveKey = ref([]);

const tableRefs = ref({});
const setItemRef = (e, item) => {
  tableRefs.value[item] = e;
};

const changeTaskAllList = (e) => {
  const vl = e.value;

  const last = vl[vl.length - 1];
  const o = form.value.rdTaskListAll.find((item) => item.id == last);
  if (!last) return;

  nextTick(() => {
    console.log(' tableRefs.value', tableRefs.value, o);

    try {
      uni.showLoading();
      getObj({ id: last })
        .then((res) => {
          if (res.code != 0) {
            uni.showToast({
              mask: true,
              title: `获取数据失败, 失败原因: ${res.msg}`,
              icon: 'none',
            });
            return;
          }
          tableRefs.value[o['taskCode']].init(res.data);
        })
        .finally(() => {
          uni.hideLoading();
        });
    } catch (error) {
      console.log('err', error);
    }
  });
};

const beforeExpend = (e) => {
  return new Promise((reslove, reject) => {
    const o = form.value.rdTaskListAll.find((item) => item.id == e);
    try {
      uni.showLoading();
      getObj({ id: e })
        .then((res) => {
          if (res.code != 0) {
            uni.showToast({
              mask: true,
              title: `获取数据失败, 失败原因: ${res.msg}`,
              icon: 'none',
            });
            return;
          }
          nextTick(() => {
            tableRefs.value[o['taskCode']].init(res.data);
            reslove(true);
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    } catch (error) {
      console.log('err', error);
      reject(false);
    }
  });
};
defineExpose({
  init,
});
</script>

<style lang="scss" scoped>
@import '../../experiment/components/table';

.block .content {
  padding: 0 !important;
}

.card-detail {
  padding: 0 !important;
}

.wd-cell {
  padding-left: 0 !important;
}

.wd-card__title {
  border-left: 4px solid #2e5cf6 !important;
}

.pm-table {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 0 30rpx;

  .pm-title {
    box-sizing: border-box;
    padding-left: 20rpx;
    margin: 40rpx 0;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-left: 8rpx solid #2e5cf6;
    border-radius: 4rpx;
  }

  .pm-row {
    display: flex;
    min-height: 60rpx;
    border-bottom: 1px solid #f6f0f0;

    .pm-label {
      display: flex;
      align-items: center;
      width: 20%;
      font-size: 26rpx;
      color: #979494;
    }

    .pm-value {
      display: flex;
      flex: 1;
      align-items: center;
      font-size: 26rpx;
      color: #333;
    }
  }
}

.sign-main {
  // display: flex;
  // align-items: center;
  // justify-content: center;
  // width: 100%;
  // margin: 20rpx 0;
  position: fixed;
  right: 0rpx;
  bottom: 40rpx;
  width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  color: white;
  text-align: center;
  background-color: rgb(77 128 240);

  // border-radius: 50%;
  border-top-left-radius: 40rpx;
  border-bottom-left-radius: 40rpx;
}

:deep(.label) {
  width: 160rpx !important;
}

.result-tag {
  padding: 6rpx 14rpx;
  margin: 2rpx 0;
  font-size: 24rpx;
  color: white;
  background-color: #87d068;
  border-radius: 4rpx;
}

.sign-main-show {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .sign-main-show-title {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #818181;
    border-bottom: 1px solid #e3e3e3;
  }

  .sign-main-show-line {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90%;
    padding: 20rpx;
    margin: 20rpx 0;
    border: 4rpx solid #d0dbff;
    border-radius: 10rpx;
  }

  .sign-main-show-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    border-top: 1px solid #e3e3e3;
  }
}

.info-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.info-list-main {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 10rpx;
  margin: 10rpx 0;
  border: 1px solid #e3e3e3;
  border-radius: 8rpx;

  .info-list-row {
    display: flex;
    width: 100%;

    .info-list-label {
      width: 150rpx;
      font-size: 28rpx;
      color: #808080;
    }

    .info-list-value {
      display: flex;
      flex: 1;
      align-items: center;
      width: 0;
      word-break: break-all;
      white-space: pre-line;
    }
  }
}

.craft-row {
  display: flex;
  align-items: center;

  .craft-row-img-main {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    width: 0;
  }
}

.craft-row-img {
  width: 240rpx;
  height: 240rpx;
}

.form-demandDesc {
  align-items: flex-start !important;

  .text {
    word-break: break-all;
  }
}

.info-row-item {
  padding: 6rpx 0;
  word-break: break-all;

  // border-bottom: 1px solid #f2f2f2;
}

.text {
  word-break: break-all;
  word-wrap: break-word;
}

:deep(.wd-collapse-item__body) {
  padding: 0 !important;
}

// :deep(.wd-collapse-item__wrapper){
//   height:auto !important;
// }
</style>
